using System.Windows.Media.Imaging;
using System.IO;
using System.Runtime.Serialization;

namespace WebSilverlight.Helpers
{
    [DataContract]
    public partial class PictureSerializableHelper
    {
        public PictureSerializableHelper(){}

        public PictureSerializableHelper(WriteableBitmap bmp)
        {
            this.Pixels = bmp.Pixels;
            this.PixelHeight = bmp.PixelHeight;
            this.PixelWidth = bmp.PixelWidth;
        }       

        [DataMember]
        public int[] Pixels { get; set; }
        [DataMember]
        public int PixelWidth { get; set; }
        [DataMember]
        public int PixelHeight { get; set; }       
    }

    public class PictureHelper
    {        
        public static WriteableBitmap WriteableBitmapFromByteArray(byte[] buffer)
        {            
            WriteableBitmap bmp = null;
            if (buffer != null && buffer.Length > 0)
            {
                MemoryStream ms = new MemoryStream(buffer);
                DataContractSerializer ser = new DataContractSerializer(typeof(PictureSerializableHelper));
                PictureSerializableHelper hlp = (PictureSerializableHelper)ser.ReadObject(ms);
                ms.Close();

                bmp = new WriteableBitmap(hlp.PixelWidth, hlp.PixelHeight);

                for (int i = 0; i < hlp.Pixels.Length; i++)
                {
                    bmp.Pixels[i] = hlp.Pixels[i];
                }
                //Buffer.BlockCopy(hlp.Pixels, 0, bmp.Pixels, 0, hlp.Pixels.Length);                
            }
            return bmp;
        }

        public static byte[] ToByteArray(WriteableBitmap bmp)
        {
            PictureSerializableHelper hlp = new PictureSerializableHelper(bmp);

            MemoryStream ms = new MemoryStream();
            DataContractSerializer ser = new DataContractSerializer(typeof(PictureSerializableHelper));
            ser.WriteObject(ms, hlp);
            byte[] array = ms.ToArray();
            ms.Close();            

            return array;
        }
    }
}
